package com.alibaba.cirtus.ots.application.adapter.ability.facade.service.sap;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap.MnSapIf004V2ServiceImpl;
import com.alibaba.cirtus.ots.application.adapter.ability.model.enums.MnSAPStatus;
import com.alibaba.cirtus.ots.application.adapter.ability.model.request.AllocateOrderSalesOrderSyncRequest;
import com.alibaba.cirtus.ots.application.adapter.ability.model.response.AllocateOrderDetailBatchGetOrgResponse;
import com.alibaba.cirtus.ots.application.adapter.ability.model.response.AllocateOrderScItemDetailDTO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.response.WarehouseResponse;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.InfoUtil;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.ResponseUtil;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.citrus.ots.common.exception.ProcessException;
import com.alibaba.citrus.ots.common.util.DateUtils;
import com.alibaba.citrus.ots.common.util.JsonUtil;
import com.alibaba.citrus.ots.common.util.SapAndCrmFieldDealUtils;
import com.alibaba.citrus.ots.common.util.TimeUtil;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.middleware.cache.runtime.service.EpochCacheService;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.bcots.model.dto.*;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.bcots.model.dto.*;
import com.epoch.app.bcots.platform_enhance.SaleOrderTag;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.bcots.service.UnifiedInventoryService;
import com.epoch.app.otsapplicationadaptersdk.materialsyncretry.model.MaterialSyncRetry;
import com.epoch.app.otsapplicationadaptersdk.materialsyncretry.service.MaterialSyncRetryService;
import com.epoch.app.otsapplicationadaptersdk.model.dto.MaterialSyncRetryLoadListRequest;
import com.epoch.app.otsapplicationadaptersdk.model.dto.MessageHeaderSDO;
import com.epoch.app.otsapplicationadaptersdk.model.dto.SapRetrySaveRequest;
import com.epoch.app.otsapplicationadaptersdk.model.enums.RetryStatus;
import com.epoch.app.otsapplicationadaptersdk.model.enums.SapApiCode;
import com.epoch.app.otsapplicationadaptersdk.sap.*;
import com.epoch.app.otsapplicationadaptersdk.sap.mnsapif004.service.MnSapIf004Service;
import com.epoch.app.otsapplicationadaptersdk.sap.mnsapif013.service.MnSapIf013Service;
import com.epoch.app.otsapplicationadaptersdk.sapretrywrite.service.SapRetryWriteService;
import com.epoch.app.otsapplicationadaptersdk.sapv2.mnsapif004v2.service.MnSapIf004V2Service;
import com.epoch.app.otsb2btradecenter.api.orderwrite.service.OrderWriteService;
import com.epoch.app.otsb2btradecenter.dto.request.ModifyOrderLineRequest;
import com.epoch.app.otsb2btradecenter.dto.request.ModifyOrderRequest;
import com.epoch.app.otsforecastsales.api.forecastorderlinequery.service.ForecastOrderLineQueryService;
import com.epoch.app.otsforecastsales.model.dto.QuerySaleUnitRequest;
import com.epoch.app.otsforecastsales.model.dto.SelectCombox;
import com.epoch.app.otsplatformenhance.api.group.scitemgroupquery.service.ScItemGroupQueryService;
import com.epoch.app.otsplatformenhance.api.organizationquery.service.OrganizationQueryService;
import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.CustomerAddressLoadListRequest;
import com.epoch.app.otsplatformenhance.domain.customeraddress.model.CustomerAddress;
import com.epoch.app.otsplatformenhance.domain.customeraddress.service.CustomerAddressService;
import com.epoch.app.otsplatformenhance.dto.request.IdQueryRequest;
import com.epoch.app.otsplatformenhance.dto.request.QueryScItemGroupRequest;
import com.epoch.app.otsplatformenhance.dto.response.ScItemGroupResponse;
import com.epoch.app.otsplatformenhance.interfacedatasyncconfigquery.service.InterfaceDataSyncConfigQueryService;
import com.epoch.app.otsplatformenhance.model.dto.BatchQueryAddress2Request;
import com.epoch.app.otsplatformenhance.model.dto.BatchQueryAddress2Response;
import com.epoch.app.otsplatformenhance.model.dto.DataCheckRequest;
import com.epoch.app.otsplatformenhance.model.enums.OrderTypeEnum;
import com.epoch.app.otsplatformenhance.model.dto.PageQueryAddressListRequest;
import com.epoch.app.otsplatformenhance.model.dto.PageQueryAddressListResponse;
import com.epoch.app.otsplatformenhance.sdo.CustomerAddressSDO;
import com.epoch.app.otsplatformenhance.service.OtsPlatformEnhanceService;
import com.epoch.app.otspricecenter.api.creditquery.service.CreditQueryService;
import com.epoch.app.otspricecenter.model.dto.CreditReponse;
import com.epoch.app.otspricecenter.model.dto.QueryCreditRequest;
import com.epoch.app.otsunifiedinventory.api.allocateorderwrite.service.AllocateOrderWriteService;
import com.epoch.app.otsunifiedinventory.api.forecastwarehouse.dto.QueryWarehouseByFactoryCodeAndWarehouseCodeRequest;
import com.epoch.app.otsunifiedinventory.api.forecastwarehouse.service.ForecastWarehouseService;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateOrderSalesOrderSyncResponse;
import com.epoch.app.otsunifiedinventory.model.dto.WarehouseInfoDTO;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @description: sap->共享平台 销售订单 退单 更新接口 F-B F-b
 * @author: yuhw
 * @date: 2021年09月27日 21:26
 **/
@Component
public class MnSapIf013ServiceImpl implements MnSapIf013Service {

    @Autowired
    private AllocateOrderWriteService allocateOrderWriteService;
    @Autowired
    private UnifiedInventoryService unifiedInventoryService;
    @Resource
    private ForecastWarehouseService forecastWarehouseService;
    @Resource
    OtsPlatformEnhanceService otsPlatformEnhanceService;
    @Autowired
    private OrderWriteService orderWriteService;
    @Autowired
    private BaseDataService baseDataService;
    @Autowired
    private ScItemGroupQueryService scItemGroupQueryService;
    @Autowired
    private ForecastOrderLineQueryService forecastOrderLineQueryService;
    @Autowired
    private CreditQueryService creditQueryService;
    @Autowired
    private OrganizationQueryService organizationQueryService;
    @Autowired
    private InterfaceDataSyncConfigQueryService interfaceDataSyncConfigQueryService;
    @Resource
    EpochCacheService epochCacheService;
    @Resource
    private SapRetryWriteService sapRetryWriteService;
    @Resource
    private CustomerAddressService customerAddressService;
    @Resource
    MaterialSyncRetryService materialSyncRetryService;
    @Resource(type = MnSapIf004ServiceImpl.class)
    MnSapIf004Service mnSapIf004Service;

    private static Log log = Log.getLogger(MnSapIf013ServiceImpl.class);
    private static final Integer MAX_PAGE_SIZE = 1000;

    private static final String ORG_CODE = "1171";
    private static final String SIX_THOUSAND_ORG_ID = "286072177888956796";

    private static String getOrgId(Map obj){
        JSONObject o = JSONObject.parseObject(JSONObject.toJSONString(obj));
        if (o != null){
            JSONArray array = o.getJSONArray("result");
            if (array != null && array.size() > 0){
                JSONObject j = array.getJSONObject(0).getJSONObject("organizationSDO");
                AllocateOrderDetailBatchGetOrgResponse r =
                        JsonUtil.convert(j,AllocateOrderDetailBatchGetOrgResponse.class);
                if (r != null){
                    return r.getId();
                }
            }
        }
        return null;
    }

    @ProcessInvoker(remark = "MnSapIf013Service", errorCode = "", printLog = true)
    @Override
    public MnSapCommResponse externalUpdateAllocateBySaleOrder(MnSapIf013Request mnSapIf013Request) {
        log.info("MnSapIf013ServiceImpl.externalUpdateAllocateBySaleOrder.request:{}",JSON.toJSONString(mnSapIf013Request));

        MnSapCommResponse check = check(mnSapIf013Request);
        log.info("MnSapIf013ServiceImpl.check.result:{}",JSON.toJSONString(mnSapIf013Request));

        if (check != null) {
            log.error("MnSapIf013ServiceImpl.externalUpdateAllocateBySaleOrder.check failed: " + JSON.toJSONString(check));
            return check;
        }

        MnSapCommResponse response = new MnSapCommResponse();
        List<MnSapCommSDO> mnSapCommSDOS = Lists.newArrayList();
        for (MnSapIf013SDO sdo : mnSapIf013Request.getData()){
            //处理送达方和售达方前置0
            sdo.setDeliveryPartCode(SapAndCrmFieldDealUtils.generateIdField(sdo.getDeliveryPartCode()));
            sdo.setSoldPartCode(SapAndCrmFieldDealUtils.generateIdField(sdo.getSoldPartCode()));

            //电商订单逻辑
            if (ORG_CODE.equals(sdo.getSaleOrganizationCode())) {
                if (SaleOrderTag.DS_STD_ORDER.getCode().equals(sdo.getOrderType())
                        || SaleOrderTag.DS_ZD_ORDER.getCode().equals(sdo.getOrderType())
                        || SaleOrderTag.DS_STD_RETURN_ORDER.getCode().equals(sdo.getOrderType())) {

                    MnSapCommResponse mnSapCommResponse = mnSapCommResponseConverter(mnSapIf013Request,sdo, response, mnSapCommSDOS);
                    //判断是否需要重试 需要则加入重试表
                    isNeedSaveRetry(mnSapCommResponse,mnSapIf013Request);
                    return mnSapCommResponse;
                }
            }


            AllocateOrderSalesOrderSyncRequest request = new AllocateOrderSalesOrderSyncRequest();
            request.setCode(sdo.getAllocateOrderId());
            request.setOutAllocateApplyOrderId(sdo.getOutAllocateApplyOrderId());
            request.setOutAllocateOrderId(sdo.getOutAllocateOrderId());
            request.setOrderType(sdo.getOrderType());
            if ("ZRE".equals(sdo.getOrderType())){
                request.setReturnOrder(true);
            }else {
                request.setReturnOrder(false);
            }
            request.setSaleOrganizationCode(sdo.getSaleOrganizationCode());
            // 组织转换
//            BaselineGetOrganizationByOutCodesRequest baselineGetOrganizationByOutCodesRequest = new BaselineGetOrganizationByOutCodesRequest();
//            baselineGetOrganizationByOutCodesRequest.setOutCodes(Lists.newArrayList(sdo.getSaleOrganizationCode()));
//            baselineGetOrganizationByOutCodesRequest.setStatus(1);
//            Map organizationMap = this.externalUpdateAllocateBySaleOrder$callAPI2(baselineGetOrganizationByOutCodesRequest);
//            String orgId = getOrgId(organizationMap);
//            // TODO 把获取预报单的请求下沉到预报单.
//            request.setApplyOrgId(orgId);

            request.setSaleChannel(sdo.getSaleChannel());
            request.setSaleDepartmentCode(sdo.getSaleDepartmentCode());

            // 产品组
            request.setProductGroup(sdo.getProductGroupCode());
            request.setSaleChannel(sdo.getSaleChannel());
            request.setSaleDepartmentCode(sdo.getSaleDepartmentCode());
            //TODO 通过售达方编码,读取客户主数据中客户的"销售办公室"字段信息
            request.setSapSalesOrgId(sdo.getSaleOrganizationCode());
            //createTime 是时分秒  年月日 在createDate上
            if (StringUtils.isNotBlank(sdo.getCreateDate())){
                if (StringUtils.isNotBlank(sdo.getCreateTime())){
                    request.setCreateTime(TimeUtil.parseYYYYMMddHHmmss(sdo.getCreateDate() + sdo.getCreateTime()));
                }else {
                    request.setCreateTime(TimeUtil.parseSimpleDateFormat(sdo.getCreateDate()));
                }
            }
//            request.setCreateTime(TimeUtil.parseSimpleDateFormat(sdo.getCreateTime()));
            request.setUpdateTime(TimeUtil.parseSimpleDateFormat(sdo.getModifyDate()));

//            request.setGmtModified(TimeUtil.parseSimpleDateFormat(sdo.getModifyDate()));
//            request.setModifyTime(TimeUtil.parseSimpleDateFormat(sdo.getModifyDate()));
            request.setDocDate(TimeUtil.parseSimpleDateFormat(sdo.getDocTime()));
            //TODO 看情况需要转换 产品组 工厂 库位 算了 从 预报单上取好了.
            QueryWarehouseByFactoryCodeAndWarehouseCodeRequest queryRequest = new QueryWarehouseByFactoryCodeAndWarehouseCodeRequest();
            queryRequest.setWarehouseCode(sdo.getInventoryCode());
            queryRequest.setFactoryCode(sdo.getFactoryCode());
            log.info("MnSapIf013ServiceImpl.queryWarehouseByFactoryCodeAndWarehouseCode.ship.request:{}",JSON.toJSONString(queryRequest));

            Result<List<WarehouseInfoDTO>> listResult = forecastWarehouseService.queryWarehouseByFactoryCodeAndWarehouseCode(queryRequest);
            log.info("MnSapIf013ServiceImpl.queryWarehouseByFactoryCodeAndWarehouseCode.ship.result:{}",JSON.toJSONString(listResult));

//            WmsQueryWarehouseZoneListRequest zoneListRequest = new WmsQueryWarehouseZoneListRequest();
//            if (StringUtils.isNotEmpty(sdo.getInventoryCode())){
//                zoneListRequest.setWarehouseCode(sdo.getInventoryCode());
//            }else {
//                zoneListRequest.setWarehouseCode("DEFAULT");
//            }
//            zoneListRequest.setSapFactoryCode(sdo.getFactoryCode());
//            WmsQueryWarehouseZoneListResponse shipResponse = unifiedInventoryService.wmsQueryWarehouseZoneList(zoneListRequest);
            String shipAreaId = getAreaId(listResult);
            if (StringUtils.isBlank(shipAreaId)){
                log.info("MnSapIf013ServiceImpl.queryWarehouseByFactoryCodeAndWarehouseCode.ship.error:{}",JSON.toJSONString(listResult));
                return ResponseUtil.fail(mnSapIf013Request,"交货工厂和库存地点查询不到对应的发货仓");
            }
            String shipWarehouseId = getWarehouseId(listResult);
            request.setShipAreaId(shipAreaId);
            request.setShipWarehouseId(shipWarehouseId);

            // TODO 收货仓 从原单据上取 收货仓 和客户
            //根据售达方和送达方查找仓库信息，查出多个返回错误，如果有值 取销售组织
            SearchCargoZoneListRequest searchCargoZoneListRequest = new SearchCargoZoneListRequest();
            searchCargoZoneListRequest.setSapSaleBPCode(sdo.getSoldPartCode());
            //售达方
            searchCargoZoneListRequest.setSapDeliveryBPCode(sdo.getDeliveryPartCode());
            log.info("根据售达方和送达方查找仓库信息入参：售达方：{},送达方:{}",sdo.getSoldPartCode(),sdo.getDeliveryPartCode());
            log.info("MnSapIf013ServiceImpl.searchCargoZoneList.receive.request:{}",JSON.toJSONString(searchCargoZoneListRequest));
            SearchCargoZoneListResponse searchCargoZoneListResponse = unifiedInventoryService.searchCargoZoneList(searchCargoZoneListRequest);
            log.info("MnSapIf013ServiceImpl.searchCargoZoneList.receive.result:{}",JSON.toJSONString(searchCargoZoneListResponse));

            log.info("根据总部售达方和总部送达方查找仓库信息出参：", JSON.toJSONString(searchCargoZoneListResponse));
            String receiveAreaId = null;
            String receiveOrgId = null;
            String orgOutCode = "";
            Boolean isDTC = null;
            String addressCode = null;
            if (searchCargoZoneListResponse != null && CollectionUtils.isNotEmpty(searchCargoZoneListResponse.getResult())
                && searchCargoZoneListResponse.getResult().size() == 1){
                WarehouseInfo warehouseInfo = searchCargoZoneListResponse.getResult().get(0);
                receiveAreaId = warehouseInfo.getId();
                receiveOrgId = warehouseInfo.getSaleOrgId();
            }else {
                if (searchCargoZoneListResponse != null && CollectionUtils.isNotEmpty(searchCargoZoneListResponse.getResult())){
                    log.info("MnSapIf013ServiceImpl.searchCargoZoneList.receive.error:{}",JSON.toJSONString(searchCargoZoneListResponse));
                    return ResponseUtil.fail(mnSapIf013Request,"售达方或送达方有误，请重新填写");
                }else {
                    //找客户的时候应该用deliveryPartCode和soldPartCode一起匹配,精确定位一条数据
                    CustomerAddressLoadListRequest customerAddressLoadListRequest = new CustomerAddressLoadListRequest();
                    customerAddressLoadListRequest.setAddressCode(SapAndCrmFieldDealUtils.generateIdField(sdo.getDeliveryPartCode()));
                    customerAddressLoadListRequest.setCustomerCode(SapAndCrmFieldDealUtils.generateIdField(sdo.getSoldPartCode()));
                    log.info("MnSapIf013ServiceImpl.searchCargoZoneList.loadCustomerAddressList2.request:{}",JSON.toJSONString(customerAddressLoadListRequest));
                    Result<List<CustomerAddress>> customerAddresslistResult = customerAddressService.loadCustomerAddressList2(customerAddressLoadListRequest);
                    log.info("MnSapIf013ServiceImpl.searchCargoZoneList.loadCustomerAddressList2.result:{}",JSON.toJSONString(customerAddresslistResult));
                    if (customerAddresslistResult != null && CollectionUtils.isNotEmpty(customerAddresslistResult.getResult())){
                        isDTC = true;
                        receiveOrgId = customerAddresslistResult.getResult().get(0).getOrgSaleOrganizationCode();

                        orgOutCode = getOrgOutCodeBySoldPartCode(sdo.getSoldPartCode());
                        addressCode = customerAddresslistResult.getResult().get(0).getId().toString();
                    }else {
                        log.info("MnSapIf013ServiceImpl.searchCargoZoneList.loadCustomerAddressList2.error:{}",JSON.toJSONString(customerAddresslistResult));
                        return ResponseUtil.fail(mnSapIf013Request,"售达方或送达方有误，请重新填写");
                    }
//                    //查找客户 和 客户编码
//                    BatchQueryAddress2Request batchQueryAddress2Request = new BatchQueryAddress2Request();
//                    batchQueryAddress2Request.setAddressCodes(Lists.newArrayList(sdo.getDeliveryPartCode()));
//                    log.info("MnSapIf013ServiceImpl.searchCargoZoneList.batchQueryAddress2.request:{}",JSON.toJSONString(batchQueryAddress2Request));
//                    BatchQueryAddress2Response batchQueryAddress2Response = otsPlatformEnhanceService.batchQueryAddress2(batchQueryAddress2Request);
//                    log.info("MnSapIf013ServiceImpl.searchCargoZoneList.batchQueryAddress2.result:{}",JSON.toJSONString(batchQueryAddress2Response));
//                    if (batchQueryAddress2Response != null && CollectionUtils.isNotEmpty(batchQueryAddress2Response.getResult())){
//                        isDTC = true;
//                        receiveOrgId = batchQueryAddress2Response.getResult().get(0).getOrgSaleOrganizationCode();
//
//                        orgOutCode = getOrgOutCodeBySoldPartCode(sdo.getSoldPartCode());
//                        addressCode = batchQueryAddress2Response.getResult().get(0).getId();
//                    }else {
//                        log.info("MnSapIf013ServiceImpl.searchCargoZoneList.batchQueryAddress2.error:{}",JSON.toJSONString(batchQueryAddress2Response));
//                        return ResponseUtil.fail(mnSapIf013Request,"售达方或送达方有误，请重新填写");
//                    }
                }
            }
            try {
                //根据配置表进行数据拦截过滤
                DataCheckRequest dataCheckRequest = new DataCheckRequest();
                dataCheckRequest.setOrderType(OrderTypeEnum.ALLOCATEORDER.getCode());
                dataCheckRequest.setOrgOutCode(getOrgCode(receiveOrgId));
                dataCheckRequest.setVariable(SapAndCrmFieldDealUtils.toDateString(sdo.getCreateDate()));
                Result<Boolean> checkResult = interfaceDataSyncConfigQueryService.dataCheck(dataCheckRequest);
                if (checkResult != null && checkResult.getResult() != null && !checkResult.getResult()){
                    log.info("013.interfaceDataSyncConfigQueryService 拦截 "+JSONObject.toJSONString(sdo));
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(sdo.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
                    mnSapCommSDO.setMessage("成功！");
                    response.setData(Lists.newArrayList(mnSapCommSDO));
                    return success(mnSapIf013Request);
                }
            } catch (Throwable e) {
                log.error("013.interfaceDataSyncConfigQueryService.Error", e);
            }

            request.setReceiveAreaId(receiveAreaId);
            request.setReceiveOrgId(StringUtils.isNotBlank(orgOutCode)?orgOutCode:receiveOrgId);
            request.setAddressCode(addressCode);
            request.setIsDTC(isDTC);



            //收货仓不修改
//            request.setReceiveWarehouseId(sdo.getFactoryCode());
//            request.setReceiveAreaId(sdo.getInventoryCode());
            request.setExpectedDeliveryDate(TimeUtil.parseSimpleDateFormat(sdo.getExpectedDeliveryTime()));
            request.setShipMethod(StringUtils.isNotBlank(sdo.getShipType())?Integer.parseInt(sdo.getShipType()):
                    null);
            request.setRemark(sdo.getRemark());
            request.setSapRefPoNo(sdo.getCustomerReferenceNo());
            request.setSapCostCenter(sdo.getCostCenter());
            request.setOrderReason(sdo.getOrderReason());
            request.setFeatures(sdo.getFeatures());
            request.setDocDate(TimeUtil.parseSimpleDateFormat(sdo.getDocTime()));
            request.setSaleOrganizationCode(sdo.getSaleOrganizationCode());
            request.setSapChannel(sdo.getSapChannel());
            request.setSapSalesOrgId(sdo.getSaleOrganizationCode());
            //设置下发时间
            request.setExt(sdo.getExt());
            List<MnSapIf013Detail> details = sdo.getItems();
            List<AllocateOrderScItemDetailDTO> scItemDetails = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(details)){
                for (MnSapIf013Detail detail : details){
                    AllocateOrderScItemDetailDTO scItemDetail = new AllocateOrderScItemDetailDTO();
                    scItemDetail.setLineNo(detail.getAllocateOrderLineId());
                    scItemDetail.setOutAllocateApplyOrderLineId(detail.getOutAllocateApplyOrderLineId());
                    scItemDetail.setOutAllocateOrderLineId(InfoUtil.deleteZeroPrefix(detail.getOutAllocateOrderLineId()));
//                    scItemDetail.setScItemCode(SapAndCrmFieldDealUtils.generateIdField(detail.getScItemId()));
                    scItemDetail.setScItemCode(subStringScItmCode(detail.getScItemId()));
//                    scItemDetail.setScItemId(SapAndCrmFieldDealUtils.generateIdField(detail.getScItemId()));
                    scItemDetail.setScItemId(subStringScItmCode(detail.getScItemId()));
                    scItemDetail.setQuantity(StringUtils.isBlank(detail.getQuantity())?null:detail.getQuantity().trim());
                    if (request.getReturnOrder()){
                        scItemDetail.setConfirmQuantity(StringUtils.isBlank(detail.getQuantity())?null:detail.getQuantity().trim());
                    }else {
                        scItemDetail.setConfirmQuantity(StringUtils.isBlank(detail.getConfirmQuantity())?null:detail.getConfirmQuantity().trim());
                    }
                    scItemDetail.setUnit(detail.getSaleUnit());
                    scItemDetail.setUnitPrice(detail.getPrice());
                    scItemDetail.setPrice(detail.getPrice());
                    scItemDetail.setSubTotalAmount(detail.getSubTotalAmount());
//                    scItemDetail.setAllocateApplyOrderLineId(detail.geta);
                    // 拒绝编码?
                    scItemDetail.setCloseCode(detail.getCloseCode());
                    scItemDetail.setClosedReason(detail.getCloseReason());
                    if (StringUtils.isNotBlank(detail.getCloseCode()) || StringUtils.isNotBlank(detail.getCloseReason())){
                        scItemDetail.setClosed(true);
                    }else {
                        scItemDetail.setClosed(false);
                    }
                    //设置预报单行号
                    scItemDetail.setAllocateApplyOrderLineId(detail.getOutAllocateApplyOrderLineId());
                    if (StringUtils.isNotBlank(sdo.getExpectedDeliveryTime())){
                        scItemDetail.setExpectedDeliveryDate(TimeUtil.parseSimpleDateFormat(sdo.getExpectedDeliveryTime()));
                    }

                    scItemDetail.setRemark(detail.getRemarks());
                    scItemDetail.setRemarks(detail.getRemarks());
                    scItemDetail.setGiftQuantity(detail.getGiftQuantity());
                    scItemDetail.setTaxRate(detail.getTaxRate());
                    scItemDetail.setFeatures(detail.getFeatures());
                    //20220327 给生产日期一个默认值
                    if (StringUtils.isBlank(detail.getExt()) || "00000000".equals(detail.getExt())){
                        scItemDetail.setExpectedProduceDate(TimeUtil.parseSimpleDateFormat("20000101"));
                    }else{
                        scItemDetail.setExpectedProduceDate(TimeUtil.parseSimpleDateFormat(detail.getExt()));
                    }
                    //2022.2.22 确认日期修改为sap传递的
                    if (StringUtils.isNotBlank(detail.getExt1())){
                        scItemDetail.setConfirmTime(TimeUtil.parseSimpleDateFormat(detail.getExt1()));
                    }
                    scItemDetails.add(scItemDetail);
                }
            }
            request.setAllocateOrderScItemDetails(scItemDetails);
            com.epoch.app.otsunifiedinventory.dto.request.AllocateOrderSalesOrderSyncRequest syncRequest =
                    JsonUtil.convert(request,
                            com.epoch.app.otsunifiedinventory.dto.request.AllocateOrderSalesOrderSyncRequest.class);
            log.info("MnSapIf013ServiceImpl.salesOrderSync.request:{}",JSON.toJSONString(syncRequest));
            Result<AllocateOrderSalesOrderSyncResponse> resultMap =  allocateOrderWriteService.salesOrderSync(syncRequest);
            log.info("MnSapIf013ServiceImpl.salesOrderSync.result:{}",JSON.toJSONString(resultMap));

            String code = null;
            if (resultMap != null && resultMap.getResult() != null){
                code = resultMap.getResult().getCode();
            }
            MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
            mnSapCommSDO.setHeaderKey(sdo.getHeaderKey());
            mnSapCommSDO.setExtId(code);
            if (StringUtils.isNotBlank(code) && code.startsWith("STO")){
                mnSapCommSDO.setMessage(MnSAPStatus.SUCCESS.getMsg());
                mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
                retry(request.getOutAllocateOrderId(),true);
            }else {
                mnSapCommSDO.setMessage(code);
                mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                mnSapCommSDO.setExtId(null);
                //写入重试队列
                saveSapRetry(mnSapIf013Request,mnSapIf013Request.getData().get(0),code );
            }
            List<MnSapCommDetail> mnSapCommDetails = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(sdo.getItems())){
                String finalCode = code;
                mnSapCommDetails = sdo.getItems().stream().map(m->{
                    MnSapCommDetail mnSapCommDetail = new MnSapCommDetail();
                    mnSapCommDetail.setItemKey(m.getItem_key());
                    if (StringUtils.isNotBlank(finalCode) && finalCode.startsWith("STO")){
                        mnSapCommDetail.setStatus(MnSAPStatus.SUCCESS.getCode());
                        mnSapCommDetail.setMessage(MnSAPStatus.SUCCESS.getMsg());
                    }else {
                        mnSapCommDetail.setStatus(MnSAPStatus.ERROR.getCode());
                        mnSapCommDetail.setMessage(finalCode);
                    }
                    return mnSapCommDetail;
                }).collect(Collectors.toList());

            }
            mnSapCommSDO.setItem(mnSapCommDetails);
            mnSapCommSDOS.add(mnSapCommSDO);
        }
        response.setData(mnSapCommSDOS);
        response.setInterfacePath(mnSapIf013Request.getMessageHeader().getInterfacePath());
        response.setMessageId(mnSapIf013Request.getMessageHeader().getMessageId());
        return response;
//        return MnSapIf013Service.super.externalUpdateAllocateBySaleOrder(mnSapIf013Request);
    }

    private MnSapCommResponse mnSapCommResponseConverter(MnSapIf013Request mnSapIf013Request,MnSapIf013SDO data ,MnSapCommResponse response ,List<MnSapCommSDO> mnSapCommSDOS) {
        ModifyOrderRequest request = new ModifyOrderRequest();

        MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();

        //根据配置表进行数据拦截过滤
        DataCheckRequest dataCheckRequest = new DataCheckRequest();
        dataCheckRequest.setOrderType(OrderTypeEnum.SALEORDER.getCode());
        dataCheckRequest.setChannelOutCode(data.getSapChannel());
        dataCheckRequest.setOrgOutCode(data.getSaleOrganizationCode());
        dataCheckRequest.setVariable(SapAndCrmFieldDealUtils.toDateString(data.getCreateDate()));
        Result<Boolean> checkResult = interfaceDataSyncConfigQueryService.dataCheck(dataCheckRequest);
        if (checkResult != null && checkResult.getResult() != null && !checkResult.getResult()){
            log.info("interfaceDataSyncConfigQueryService 拦截 "+ data.getOutAllocateOrderId());
            mnSapCommSDO.setStatus("S");
            mnSapCommSDO.setMessage("成功");
            mnSapCommSDOS.add(mnSapCommSDO);
            response.setData(mnSapCommSDOS);
            return success(mnSapIf013Request);
        }

        request.setOrderType(data.getOrderType());
        request.setOutOrderId(data.getOutAllocateOrderId());
        //sap销售组织信息->平台
        List<String> outCodes = new ArrayList<>();
        outCodes.add(data.getSaleOrganizationCode());
        BaselineGetOrganizationByOutCodes2Request byOutCodes2Request = new BaselineGetOrganizationByOutCodes2Request();
        byOutCodes2Request.setOutCodes(outCodes);
        byOutCodes2Request.setStatus(1);
//        Map saleOrgMap = externalSyncSaleOrder$getOrganizationByOutCodes(outCodesRequest);
        BaselineGetOrganizationByOutCodes2Response byOutCodes2Response =  baseDataService.baselineGetOrganizationByOutCodes2(byOutCodes2Request);

//        JSONArray saleJsonArray = JSONObject.parseObject(JSONObject.toJSONString(saleOrgMap)).getJSONArray("result");
        if (byOutCodes2Response == null || CollectionUtils.isEmpty(byOutCodes2Response.getResult())) {
            mnSapCommSDO.setStatus("E");
            mnSapCommSDO.setMessage("销售组织转换失败");
            mnSapCommSDO.setErrCode("OTS-05-001-10-16-049");
            mnSapCommSDOS.add(mnSapCommSDO);
            response.setData(mnSapCommSDOS);
            log.error("MnSapIf015Service.externalSyncSaleOrder error: " + JSON.toJSONString(response));
            return response;
        }

        Map<String,OrganizationSDO> organizationSDOMap = byOutCodes2Response.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getOutCode,org -> org,(k1,k2)->k2));
        if (organizationSDOMap.get(data.getSaleOrganizationCode()) != null) {
            OrganizationSDO organizationSDO = organizationSDOMap.get(data.getSaleOrganizationCode());
            request.setSaleOrganizationCode(organizationSDO.getId());
            request.setSaleOrganizationName(organizationSDO.getName());
        }else {
            mnSapCommSDO.setStatus("E");
            mnSapCommSDO.setMessage("销售组织转换失败");
            mnSapCommSDO.setErrCode("OTS-05-001-10-16-049");
            mnSapCommSDOS.add(mnSapCommSDO);
            response.setData(mnSapCommSDOS);
            log.error("MnSapIf015Service.externalSyncSaleOrder error: " + JSON.toJSONString(response));
            return response;
        }

        //sap业务渠道->平台
        BaselineQueryChannelByPageRequest channelByPageRequest = new BaselineQueryChannelByPageRequest();
        channelByPageRequest.setOutCode(data.getSapChannel());
        Map map = (Map) baseDataService.baselineQueryChannelByPage(channelByPageRequest);
        JSONObject jsonMap = JSONObject.parseObject(JSONObject.toJSONString(map));
        JSONArray jsonArray = jsonMap.getJSONObject("result").getJSONArray("content");
        if (CollectionUtils.isEmpty(jsonArray)) {
            mnSapCommSDO.setStatus("E");
            mnSapCommSDO.setMessage("业务渠道转换失败");
            mnSapCommSDO.setErrCode("999");
            mnSapCommSDOS.add(mnSapCommSDO);
            response.setData(mnSapCommSDOS);
            log.error("MnSapIf013Service.externalUpdateAllocateBySaleOrder error: " + JSON.toJSONString(response));
            return response;
        }
        JSONObject jsonObject1 = jsonArray.getJSONObject(0);
        request.setSapChannel(jsonObject1.getString("channelCode"));
        request.setSapChannelName(jsonObject1.getString("channelName"));

        //sap货品组编码->平台
        QueryScItemGroupRequest scItemGroupRequest = new QueryScItemGroupRequest();
        Result<ScItemGroupResponse> scItemGroup = scItemGroupQueryService.getScItemGroup(scItemGroupRequest);
        if (scItemGroup.getResult() == null) {
            mnSapCommSDO.setStatus("E");
            mnSapCommSDO.setMessage("货品组编码转换失败");
            mnSapCommSDO.setErrCode("999");
            mnSapCommSDOS.add(mnSapCommSDO);
            response.setData(mnSapCommSDOS);
            log.error("MnSapIf013Service.externalUpdateAllocateBySaleOrder error: " + JSON.toJSONString(response));
            return response;
        }
        request.setProductGroupCode(scItemGroup.getResult().getCode());
        request.setProductGroupName(scItemGroup.getResult().getName());

        request.setCreator(data.getCreator());
        request.setModifier(data.getModifier());
        request.setCreateDate(SapAndCrmFieldDealUtils.toDateString(data.getCreateDate()));
        request.setCreateTime(SapAndCrmFieldDealUtils.toDateString(data.getCreateTime()));
        if (!"00000000".equals(data.getModifyDate())) {
            request.setGmtModified(SapAndCrmFieldDealUtils.toDateString(data.getModifyDate()));
        }
        request.setBeginTime(SapAndCrmFieldDealUtils.toDateString(data.getDocTime()));


        //sap客户编码、客户收货地址编码->平台
        PageQueryAddressListRequest pageQueryAddressListRequest = new PageQueryAddressListRequest();
        pageQueryAddressListRequest.setAddressCode(data.getDeliveryPartCode());
        pageQueryAddressListRequest.setCustomerCode(data.getSoldPartCode());
        pageQueryAddressListRequest.setOrgSaleOrganizationCode(request.getSaleOrganizationCode());
        pageQueryAddressListRequest.setChannelCode(request.getSapChannel());
        pageQueryAddressListRequest.setItemGroup(data.getProductGroupCode());

        PageQueryAddressListResponse listResult = otsPlatformEnhanceService.pageQueryAddressList(pageQueryAddressListRequest);
        if (CollectionUtils.isEmpty(listResult.getResult())) {
            mnSapCommSDO.setStatus("E");
            mnSapCommSDO.setMessage("客户编码、收货地址转换失败");
            mnSapCommSDO.setErrCode("999");
            mnSapCommSDOS.add(mnSapCommSDO);
            response.setData(mnSapCommSDOS);
            log.error("MnSapIf013Service.externalUpdateAllocateBySaleOrder error: " + JSON.toJSONString(response));
            return response;
        }
        CustomerAddressSDO customerAddressSDO = listResult.getResult().get(0);
        request.setSoldPartCode(customerAddressSDO.getCustomerCode());
        request.setSoldPartName(customerAddressSDO.getCustomerName());
        request.setDeliveryPartCode(customerAddressSDO.getAddressCode());
        request.setDeliveryPartName(customerAddressSDO.getAddressName());
        request.setContactor(customerAddressSDO.getContactName());
        request.setContactorPhone(customerAddressSDO.getCellphoneNumber());

        request.setSaleDepartmentCode(customerAddressSDO.getOrgSaleDepartmentCode());
        request.setSaleDepartmentName(customerAddressSDO.getOrgSalesDepartmentName());
        request.setSaleChannelCode(customerAddressSDO.getOrgSaleChannelCode());
        request.setSaleChannelName(customerAddressSDO.getOrgSalesChannelName());
        //查询部门名称
        if(StringUtils.isEmpty(customerAddressSDO.getOrgSaleDepartmentCode())){
            log.info("MnSapIf015Service.externalSyncSaleOrder:客户送达方未关联销售部门信息");
        }else {
            IdQueryRequest idQueryRequest = new IdQueryRequest();
            idQueryRequest.setId(customerAddressSDO.getOrgSaleDepartmentCode());
            Result<com.epoch.app.otsplatformenhance.sdo.OrganizationSDO>  organizationSDOResult = organizationQueryService.getOrganizationDetail(idQueryRequest);
            if (organizationSDOResult != null && organizationSDOResult.getResult() != null ){
                request.setSaleDepartmentName(organizationSDOResult.getResult().getName());
            }else {
                log.info("MnSapIf015Service.externalSyncSaleOrder:未查询到销售部门 "+ JSON.toJSONString(organizationSDOResult));
            }
        }
        if( StringUtils.isEmpty(customerAddressSDO.getOrgSaleChannelCode())){
            log.info("MnSapIf015Service.externalSyncSaleOrder:客户送达方未关联销售渠道信息");
        }else {
            IdQueryRequest idQueryRequest = new IdQueryRequest();
            idQueryRequest.setId(customerAddressSDO.getOrgSaleChannelCode());
            Result<com.epoch.app.otsplatformenhance.sdo.OrganizationSDO>  organizationSDOResult = organizationQueryService.getOrganizationDetail(idQueryRequest);
            if (organizationSDOResult != null && organizationSDOResult.getResult() != null ){
                request.setSaleChannelName(organizationSDOResult.getResult().getName());
            }else {
                log.info("MnSapIf015Service.externalSyncSaleOrder:未查询到销售渠道 "+ JSON.toJSONString(organizationSDOResult));
            }
        }

        request.setExpectedDeliveryTime(SapAndCrmFieldDealUtils.toDateString(data.getExpectedDeliveryTime()));
        request.setShipType(data.getShipType());
        request.setRemark(data.getRemark());
        request.setCustomerReferenceNo(data.getCustomerReferenceNo());
        request.setCashCustomerName(data.getCostCenter());
        request.setCostCenter(data.getCostCenter());
        request.setCreateReason(data.getOrderReason());
        //request.setPriceTime(SapAndCrmFieldDealUtils.toDateString(data.getPriceTime()));
        request.setFeatures(data.getFeatures());

        mnSapCommSDO.setStatus("S");
        mnSapCommSDO.setMessage("成功");


        if (CollectionUtils.isNotEmpty(data.getItems())) {
            List<MnSapCommDetail> mnSapCommDetails = new ArrayList<>();
            List<ModifyOrderLineRequest> orderLineRequests = new ArrayList<>();
            for (MnSapIf013Detail detail : data.getItems()) {
                MnSapCommDetail mnSapCommDetail = new MnSapCommDetail();
                mnSapCommDetail.setItemKey(detail.getItem_key());

                ModifyOrderLineRequest lineRequest = new ModifyOrderLineRequest();
                //lineRequest.setOrderLineId(SapAndCrmFieldDealUtils.generateIdField(detail.getOrderLineId()));
                lineRequest.setOutOrderLineId(SapAndCrmFieldDealUtils.generateIdField(detail.getOutAllocateOrderLineId()));
                //sap货品->平台

//                QueryScItemRequest queryScItemRequest = new QueryScItemRequest();
//                queryScItemRequest.setOuterId(SapAndCrmFieldDealUtils.generateIdField(detail.getScItemId()));
//                Result<List<ScItemSDO>> scItemList = scItemQueryService.pageQueryScItemList(queryScItemRequest);

                SearchScItemRequest searchScItemRequest = new SearchScItemRequest();
                SearchReqDTO searchReqDTO = new SearchReqDTO();
                List<String> list = new ArrayList<>();
                list.add(SapAndCrmFieldDealUtils.generateScItemIdField(detail.getScItemId()));
                searchReqDTO.setOuterIdList(list);
                //2022.06.07 商品如果删除了 也算查到商品
                searchReqDTO.setStatusList(Lists.newArrayList(1,-1));
                searchScItemRequest.setSearchReqDTO(searchReqDTO);
                Result<List<com.epoch.app.bcots.model.dto.ScItemSDO>> scItemList = baseDataService.searchScItem(searchScItemRequest);

                if (scItemList.isSuccess() && CollectionUtils.isNotEmpty(scItemList.getResult())) {
                    ScItemSDO scItemSDO = scItemList.getResult().get(0);

                    lineRequest.setScItemOutCode(scItemSDO.getOuterId());
                    lineRequest.setScItemName(scItemSDO.getTitle());
                    lineRequest.setScItemId(scItemSDO.getScItemId());
                    Map<String, String> features = scItemSDO.getFeatures();
                    if (MapUtils.isNotEmpty(features)) {
                        String unitName = features.get("unit");
                        String unitCode = features.get("unitName");
                        lineRequest.setCategoryCode(features.get("category"));
                        lineRequest.setCategoryDesc(features.get("categoryDesc"));
                        lineRequest.setCategoryChildCode(features.get("categoryChildCode"));
                        lineRequest.setCategoryChildDesc(features.get("categoryChildDesc"));
                        if (StringUtils.isNotBlank(unitName)) {
                            lineRequest.setInventoryUnit(unitName);
                        }
                        if (StringUtils.isNotBlank(unitCode)) {
                            lineRequest.setInventoryUnitCode(unitCode);
                        }
                    }
                    //todo 接口未取到库存单位名称
//                        build.setInventoryUnitCode(scItemSDO.getUnit());
//                        build.setInventoryUnit(scItemSDO.getUnit());
                    QuerySaleUnitRequest querySaleUnitRequest = QuerySaleUnitRequest.builder().scItemId(scItemSDO.getScItemId()).build();
                    querySaleUnitRequest.setInventoryUnit(lineRequest.getInventoryUnit());
                    querySaleUnitRequest.setInventoryUnitCode(lineRequest.getInventoryUnitCode());
                    querySaleUnitRequest.setUnitConvert("1");
                    Result<List<SelectCombox>> querySaleUnitList = forecastOrderLineQueryService.querySaleUnitList(querySaleUnitRequest);
                    if (querySaleUnitList.isSuccess() && Objects.nonNull(querySaleUnitList.getResult())) {
                        List<SelectCombox> result = querySaleUnitList.getResult();
                        Map<String, SelectCombox> unitMap = new HashMap<>();
                        Nullable.stream(result).forEach(t -> {
                            unitMap.put(t.getValue(), t);
                        });
                        SelectCombox selected = unitMap.get(detail.getSaleUnit());
                        if (selected != null) {
                            lineRequest.setSaleUnitName(selected.getLabel());
                            lineRequest.setUnitConvert(selected.getExt());
                        }

                        SelectCombox inventoryMap = unitMap.get(detail.getSaleUnit());
                        if (inventoryMap != null) {
                            lineRequest.setInventoryUnit(inventoryMap.getLabel());
//                                build.setUnitConvert(inventoryMap.getExt());
                        }
//                            build.setInventoryUnit(map1.get(scItemSDO.getUnit()));
                    }
                }

                if (CollectionUtils.isEmpty(scItemList.getResult())) {
                    log.error("MnSapIf013ServiceImpl_scItemConvertError:{}",detail.getScItemId());
                    List<MnSapCommDetail> commDetails = new ArrayList<>();
                    mnSapCommSDO.setStatus("E");
                    mnSapCommSDO.setMessage("货品编码转换失败");
                    mnSapCommDetail.setStatus("E");
                    mnSapCommDetail.setMessage("货品编码转换失败");
                    commDetails.add(mnSapCommDetail);
                    mnSapCommSDO.setItem(commDetails);
                    mnSapCommSDOS.add(mnSapCommSDO);
                    response.setData(mnSapCommSDOS);
                    log.error("MnSapIf013Service.externalUpdateAllocateBySaleOrder error: " + JSON.toJSONString(response));
                    return response;
                }

                lineRequest.setQuantity(SapAndCrmFieldDealUtils.toInteger(detail.getQuantity()).toString());
                lineRequest.setSaleUnit(detail.getSaleUnit());
                lineRequest.setPrice(extracted(detail.getPrice()));
                lineRequest.setSubTotalAmount(extracted(detail.getSubTotalAmount()));
                lineRequest.setCloseCode(detail.getCloseCode());
                lineRequest.setCloseReason(detail.getCloseReason());


                WmsQueryWarehouseZoneListRequest warehouseZoneListRequest = new WmsQueryWarehouseZoneListRequest();
                warehouseZoneListRequest.setSapFactoryCode(data.getFactoryCode());
                warehouseZoneListRequest.setWarehouseCode(data.getInventoryCode());
                WmsQueryWarehouseZoneListResponse warehouseZoneList = unifiedInventoryService.wmsQueryWarehouseZoneList(warehouseZoneListRequest);
                if (CollectionUtils.isNotEmpty(warehouseZoneList.getResult())) {
                    WarehouseInfo warehouseInfo = warehouseZoneList.getResult().get(0);
                    lineRequest.setWarehouseCode(warehouseInfo.getId());
                    lineRequest.setWarehouseName(warehouseInfo.getName());
                }
                lineRequest.setFactoryCode(data.getFactoryCode());
                lineRequest.setInventoryCode(data.getInventoryCode());


                orderLineRequests.add(lineRequest);

                mnSapCommDetail.setStatus("S");
                mnSapCommDetail.setMessage("成功");
                mnSapCommDetails.add(mnSapCommDetail);
            }
            mnSapCommSDO.setItem(mnSapCommDetails);
            request.setModifyOrderLineRequests(orderLineRequests);

            //查询客户账款
            QueryCreditRequest queryCreditRequest = new QueryCreditRequest();
            queryCreditRequest.setOrganizationCode(request.getSaleOrganizationCode());
            queryCreditRequest.setChannelCode(request.getSapChannel());
            queryCreditRequest.setItemGroupCode(request.getProductGroupCode());
            queryCreditRequest.setCustomerCode(request.getSoldPartCode());
            Result<CreditReponse> result = creditQueryService.queryCreditBalance(queryCreditRequest);
            if (result.getResult() != null) {
                request.setCustomerAccounts(result.getResult().getBalance());
            }
        }
        log.info("request:" + request);
        try {
            orderWriteService.modifySaleOrder(request);
        } catch (Exception e) {
            log.error("MnSapIf013 modifySaleOrder :" + e);
            throw new ProcessException("OTS-05-001-10-16-048");
        }

        mnSapCommSDO.setStatus("S");
        mnSapCommSDO.setMessage("成功");
        mnSapCommSDOS.add(mnSapCommSDO);
        response.setData(mnSapCommSDOS);
        log.info("执行结束");
        return response;
    }

    /**
     * 根据map来获取
     * @param map
     * @return
     */
    public static String getCode(Map map){
        JSONObject obj = JSONObject.parseObject(JSONObject.toJSONString(map));
        if (obj != null){
            obj = obj.getJSONObject("result");
            if (obj != null){
                obj = obj.getJSONObject("result");
                if (obj != null){
                    return obj.getString("code");
                }
            }
        }
        return null;
    }
    public static String getWarehouseId(WmsQueryWarehouseZoneListResponse response){
        if (response != null && CollectionUtils.isNotEmpty(response.getResult())){
            WarehouseResponse warehouseResponse = JsonUtil.convert(response.getResult().get(0),
                    WarehouseResponse.class);
            return warehouseResponse.getWarehouseId();
        }
        return null;
    }
    public static String getWarehouseId(Result<List<WarehouseInfoDTO>> result){
        if (result != null && CollectionUtils.isNotEmpty(result.getResult())){
            WarehouseInfoDTO warehouseInfoDTO = result.getResult().get(0);
            return warehouseInfoDTO.getWarehouseId();
        }
        return null;
    }
    public static String getAreaId(Result<List<WarehouseInfoDTO>> result){
        if (result != null && CollectionUtils.isNotEmpty(result.getResult())){
            WarehouseInfoDTO warehouseInfoDTO = result.getResult().get(0);
            return warehouseInfoDTO.getId();
        }
        return null;
    }

    public static String getAreaId(WmsQueryWarehouseZoneListResponse response){
        if (response != null && CollectionUtils.isNotEmpty(response.getResult())){
            WarehouseResponse warehouseResponse = JsonUtil.convert(response.getResult().get(0),
                    WarehouseResponse.class);
            return warehouseResponse.getId();
        }
        return null;
    }

    public static MnSapCommResponse check(MnSapIf013Request request){
        if (CollectionUtils.isEmpty(request.getData()))return ResponseUtil.fail(request,"传递的调拨单参数列表为空");
        String msg = null;
        for (MnSapIf013SDO sdo : request.getData()) {
            if (StringUtils.isBlank(sdo.getOutAllocateOrderId())){
                msg = "outAllocateOrderId不能为空";
                break;
            }
            if (StringUtils.isBlank(sdo.getOrderType())){
                msg = "orderType 不能为空";
                break;
            }
            if (StringUtils.isBlank(sdo.getSaleOrganizationCode())){
                msg = "saleOrganizationCode 不能为空";
            }
            if (StringUtils.isBlank(sdo.getSapChannel())){
                msg = "sapChannel 不能为空";
                break;
            }
            if (StringUtils.isBlank(sdo.getProductGroupCode())){
                msg = "productGroupCode 不能为空";
                break;
            }
            if (StringUtils.isBlank(sdo.getSoldPartCode())){
                msg = "soldPartCode 不能为空";
                break;
            }
            //说工厂可以不传库存地点
//            if (StringUtils.isBlank(sdo.getInventoryCode())){
//                msg = "inventoryCode 不能为空";
//                break;
//            }
            if (StringUtils.isBlank(sdo.getDeliveryPartCode())){
                msg = "deliveryPartCode 不能为空";
                break;
            }
            if (StringUtils.isBlank(sdo.getFactoryCode())){
                msg = "factoryCode 不能为空";
                break;
            }
            if (StringUtils.isBlank(sdo.getShipType())){
                //运输方式默认值
                sdo.setShipType("1");
//                msg = "shipType 不能为空";
//                break;
            }
            if (CollectionUtils.isEmpty(sdo.getItems())){
                msg = "items 不能为空";
                break;
            }
            //修改时间 格式为20220307111350.3513180 前面年月日时分秒 后面是 0.3513180
            if (StringUtils.isBlank(sdo.getExt())){
                msg = "ext修改时间不能为空";
                break;
            }else {
                String[] split = sdo.getExt().split("\\.");
                if (split.length != 2){
                    msg = "ext修改时间 格式错误";
                    break;
                }
            }

            for (MnSapIf013Detail detail : sdo.getItems()){
                if (StringUtils.isBlank(detail.getOutAllocateOrderLineId())){
                    return ResponseUtil.fail(request,"outAllocateOrderLineId 不能为空");
                }
                if (StringUtils.isBlank(detail.getScItemId())){
                    return ResponseUtil.fail(request,"scItemId 不能为空");
                }
                if (StringUtils.isBlank(detail.getQuantity())){
                    return ResponseUtil.fail(request,"quantity 不能为空");
                }
//                if (StringUtils.isBlank(detail.getConfirmQuantity())){
//                    return ResponseUtil.fail(request,"confirmQuantity 不能为空");
//                }
//                if (StringUtils.isBlank(detail.getPrice())){
//                    return ResponseUtil.fail(request,"price 不能为空");
//                }
                if (StringUtils.isBlank(detail.getSaleUnit())){
                    return ResponseUtil.fail(request,"unit 不能为空");
                }
                if (StringUtils.isNotBlank(detail.getCloseCode()) || StringUtils.isNotBlank(detail.getCloseReason())){
                    if (StringUtils.isNotBlank(detail.getQuantity())){
                        BigDecimal decimal = new BigDecimal(detail.getQuantity().trim());
                        if (decimal.intValue() <= 0){
                            return ResponseUtil.fail(request,"非关闭情况下数量不能小于等于0");
                        }
                    }
                }
//                if (StringUtils.isBlank(detail.getCloseCode())){
//                    return ResponseUtil.fail(request,"isClosed 不能为空");
//                }
            }
            //判断是否有重复的物流
            List<String> collect = sdo.getItems().stream().map(x -> {
//                return SapAndCrmFieldDealUtils.generateIdField(x.getScItemId());
                return subStringScItmCode(x.getScItemId());
            }).distinct().collect(Collectors.toList());
            if (CollectionUtils.isEmpty(collect)){
                return ResponseUtil.fail(request,"有效items不能为空");
            }
            //物料 去0后不能重复 2022.04.25 去掉物料编码不能重复的校验 如果是分子公司的校验放在后面
//            if (collect.size() < sdo.getItems().size()){
//                return ResponseUtil.fail(request,"物料编码不能重复");
//            }
        }
        if (msg != null){
            return ResponseUtil.fail(request,msg);
        }
        return null;
    }


    public static String getWarehouseId(SearchCargoZoneListResponse response){
        if (response != null && CollectionUtils.isNotEmpty(response.getResult())){
            WarehouseInfo warehouseInfo = JsonUtil.convert(response.getResult().get(0), WarehouseInfo.class);
            return warehouseInfo.getId();
        }
        return null;
    }
    /**
     * 截取scItemCode 固定长度为12
     * @param str
     * @return
     */
    public static String subStringScItmCode(String str){
        if (StringUtils.isBlank(str)){
            return null;
        }
        if (str.length()>12){
            return str.substring(str.length()-12);
        }
        return str;
    }

    public  String getOrgCode(String orgId){
        //发货收货仓的组织id name
        BaselineGetOrganizationByIdsRequest r = new BaselineGetOrganizationByIdsRequest();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(orgId)){
            r.setIds(Lists.newArrayList(orgId));
            Object obj = baseDataService.baselineGetOrganizationByIds(r);
            JSONObject o = JSONObject.parseObject(JSONObject.toJSONString(obj));
            if (o != null){
                JSONArray array = o.getJSONArray("result");
                if (array != null && array.size() > 0){
                    JSONObject j = array.getJSONObject(0).getJSONObject("organizationSDO");
                    if (j != null){
                        return j.getString("code");
                    }
                }
            }
        }
        return null;
    }
    /**
     * 价格字段放大100倍防止精度
     * @param s
     * @return
     */
    private static String extracted(String s) {
        if (StringUtils.isBlank(s)) {
            return null;
        }
        BigDecimal val = new BigDecimal(s.trim());
        val = val.multiply(new BigDecimal(100)).setScale(0, RoundingMode.DOWN);
        return val.toString();
    }

    public static MnSapCommResponse success(MnSapIf013Request request){
        MnSapCommResponse response = new MnSapCommResponse();
        MessageHeaderSDO messageHeaderSDO = request.getMessageHeader();
        if (CollectionUtils.isNotEmpty(request.getData())){
            List<MnSapCommSDO> mnSapCommSDOS = Lists.newArrayList();
            for (MnSapIf013SDO mnSapIf013SDO : request.getData()) {
                MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                mnSapCommSDO.setHeaderKey(mnSapIf013SDO.getHeaderKey());
                mnSapCommSDO.setExtId(null);
                mnSapCommSDO.setMessage(MnSAPStatus.SUCCESS.getMsg());
                mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
                List<MnSapCommDetail> mnSapCommDetails = Lists.newArrayList();
                if (CollectionUtils.isNotEmpty(mnSapIf013SDO.getItems())) {
                    mnSapCommDetails = mnSapIf013SDO.getItems().stream().map(m -> {
                        MnSapCommDetail mnSapCommDetail = new MnSapCommDetail();
                        mnSapCommDetail.setItemKey(m.getItem_key());
                        mnSapCommDetail.setStatus(MnSAPStatus.SUCCESS.getCode());
                        mnSapCommDetail.setMessage(MnSAPStatus.SUCCESS.getMsg());
                        return mnSapCommDetail;
                    }).collect(Collectors.toList());
                    mnSapCommSDO.setItem(mnSapCommDetails);
                }
                mnSapCommSDOS.add(mnSapCommSDO);
            }
            response.setData(mnSapCommSDOS);
        }
        if (Objects.nonNull(messageHeaderSDO)) {
            response.setInterfacePath(messageHeaderSDO.getInterfacePath());
            response.setMessageId(messageHeaderSDO.getMessageId());
        }
        return response;
    }

    public  String getOrgOutCodeBySoldPartCode(String soldPartCode){
        if (StringUtils.isBlank(soldPartCode)){
            return getOrgOutCodeByHeadquartersCode("6000");
        }
        String outSoldPartCode = getOrgOutCodeByHeadquartersCode(soldPartCode);
        if (StringUtils.isBlank(outSoldPartCode)){
            return getOrgOutCodeByHeadquartersCode("6000");
        }else{
            return outSoldPartCode;
        }
    }
    private String getOrgOutCodeByHeadquartersCode(String soldPartCode){
        BaselineGetOrganizationByCodes2Request baselineGetOrganizationByCodes2Request = new BaselineGetOrganizationByCodes2Request();
        baselineGetOrganizationByCodes2Request.setIds(Lists.newArrayList(soldPartCode));
        BaselineGetOrganizationByCodes2Response baselineGetOrganizationByCodes2Response = baseDataService.baselineGetOrganizationByCodes2(baselineGetOrganizationByCodes2Request);
        if (Objects.nonNull(baselineGetOrganizationByCodes2Response)&&CollectionUtils.isNotEmpty(baselineGetOrganizationByCodes2Response.getResult())){
            String outcode = baselineGetOrganizationByCodes2Response.getResult().get(0).getId();
            if (org.apache.commons.lang.StringUtils.isNotBlank(outcode)){
                return outcode;
            }
        }
        return "";
    }

    /**
     * 保存sap重试记录
     *
     */
    public void saveSapRetry(MnSapIf013Request request,MnSapIf013SDO sdo, String code){
        try{
            if (request == null ||(StringUtils.isNotBlank(code) && code.startsWith("STO"))){
                return;
            }
            SapRetrySaveRequest sapRetrySaveRequest = new SapRetrySaveRequest();
            String requestJson = JSON.toJSONString(request);
            sapRetrySaveRequest.setParam(requestJson);
            sapRetrySaveRequest.setMsg(code);
            sapRetrySaveRequest.setMessageId(request.getMessageHeader().getMessageId());
            //请求时间戳
            sapRetrySaveRequest.setRequestTime(sdo.getExt());
            sapRetrySaveRequest.setApiCode(SapApiCode.SAP013.getValue());
            sapRetrySaveRequest.setOutKey(sdo.getOutAllocateOrderId());
            sapRetrySaveRequest.setStatus(RetryStatus.FAIL.getValue());
            sapRetryWriteService.save(sapRetrySaveRequest);
        }catch (Throwable e){
            log.error("sapRetrySaveError",e);
        }
    }
    //013走预报销售逻辑的销售单
    void isNeedSaveRetry(MnSapCommResponse mnSapCommResponse,MnSapIf013Request mnSapIf013Request){
        try{
            if (Objects.nonNull(mnSapCommResponse) && CollectionUtils.isNotEmpty(mnSapCommResponse.getData())
                    && Objects.nonNull(mnSapCommResponse.getData().get(0))){
                if (!"S".equalsIgnoreCase(mnSapCommResponse.getData().get(0).getStatus())){
                    saveSapRetry(mnSapIf013Request,mnSapIf013Request.getData().get(0),
                            mnSapCommResponse.getData().get(0).getMessage());
                }
            }
        }catch (Throwable e){
            log.error("sapRetrySaveError",e);
        }
    }

    //重试004先于调拨单的物料凭证
    private void retry(String outAllocateOrderId,boolean canRetry){
        if (!canRetry){
            return;
        }
        MaterialSyncRetryLoadListRequest materialSyncRetryLoadListRequest = new MaterialSyncRetryLoadListRequest();
        materialSyncRetryLoadListRequest.setOutOrderId(outAllocateOrderId);
        materialSyncRetryLoadListRequest.setStatus(0);
        materialSyncRetryLoadListRequest.setLimit(MAX_PAGE_SIZE);
        Result<List<MaterialSyncRetry>> listResult = materialSyncRetryService.loadList(materialSyncRetryLoadListRequest);
        if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
            for (MaterialSyncRetry materialSyncRetry : listResult.getResult()) {
                try {
                    MnSapIf004Request mnSapIf004Request = JSON.parseObject(materialSyncRetry.getRequestParams(),MnSapIf004Request.class);
                    mnSapIf004Service.externalSyncMaterial(mnSapIf004Request);
                }catch (Throwable e){
                    log.error("MnSapIf013ServiceImpl_retry",e);
                    log.error("MnSapIf013ServiceImpl_retry,request:{},004:{}",JSON.toJSONString(outAllocateOrderId),JSON.toJSONString(listResult.getResult()));
                }
                continue;
            }
        }
    }
}
